
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.util.Observable;
import java.util.Observer;
import java.util.Random;

import javax.swing.JFrame;

/**
 * @author leejun.happy@gmail.com
 * @date 2017年7月17日 上午9:49:24
 * @describe
 */

public class TankView implements Observer {

	public static final int WIDTH = 800;
	public static final int HEIGHT = 600;

	Canvas paintCanvas = null;
	Image offScreenImage = null;

	TankControl control = null;
	
	public TankView(TankControl control) {

		this.control = control;

		JFrame jFrame = new JFrame();
		jFrame.setTitle("TANK");

		paintCanvas = new Canvas();
		paintCanvas.setSize(WIDTH, HEIGHT);
		paintCanvas.addKeyListener(control);

		jFrame.add(paintCanvas);
		jFrame.pack();
		jFrame.setLocation(200, 300);
		jFrame.setResizable(false);
		jFrame.addKeyListener(control);
		jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		jFrame.setVisible(true);
	}

	void redraw() {
		Graphics g = paintCanvas.getGraphics();
		g.setColor(Color.GREEN);
		g.fillRect(0, 0, WIDTH, HEIGHT);

		control.model.draw(g);
		
		for (int i = 0; i < TankControl.tanks.size(); i++) {
			Tank t = TankControl.tanks.get(i);
			t.draw(g);
			t.move();
			if (new Random().nextInt(100) > 98) {
				t.fire();
			}
		}

		g.setColor(Color.BLACK);
		g.drawString("shells count:" + TankControl.shells.size(), 10, 10);
		g.drawString("tanks count:" + TankControl.tanks.size(), 10, 30);

		for (int i = 0; i < TankControl.shells.size(); i++) {
			Shell shell = TankControl.shells.get(i);
			shell.draw(g);
			shell.hitTanks(TankControl.tanks);
			shell.hitTank(control.model);
		}
	}

	public void update(Observable o, Object arg) {
		redraw();
	}

	public static void main(String[] args) {
		Tank model = new Tank();
		TankControl control = new TankControl(model);
		TankView view = new TankView(control);
		model.addObserver(view);
		(new Thread(model)).start();
	}
}
